package com.kevin.design.creationalPattern.singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class DoubleCheckingLockingOfLoadBalancer {
    public static void main(String[] args) {
        LoadBalancer instance1 = LoadBalancerDCL.getInstance();
        LoadBalancer instance2 = LoadBalancerDCL.getInstance();
        if (instance1 == instance2){
            System.out.println("负载均衡器是唯一的");
        }
        instance1.addServer("server1");
        instance2.addServer("server2");
        for (int i=0;i<10;i++){
            System.out.println("服务器：" + instance1.getServer());
        }
    }
}

class LoadBalancerDCL implements LoadBalancer{

    private static volatile LoadBalancer instance;

    private List<String> serverList ;

    private LoadBalancerDCL(){
        serverList = new ArrayList<>();
    }

    public static LoadBalancer getInstance(){
        if (instance == null){
            synchronized (LoadBalancerDCL.class){
                if (instance == null){
                    instance = new LoadBalancerDCL();
                }
            }
        }
        return instance;
    }

    public void addServer(String server){
        serverList.add(server);
    }

    @Override
    public void removeServer(String server) {
        serverList.remove(server);
    }

    @Override
    public String getServer() {
        Random random = new Random();
        int i = random.nextInt(serverList.size());
        return serverList.get(i);
    }
}
